package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.判断这次请求是否需要处理
        //获取本次请求的url
        String requestURI = request.getRequestURI();
        log.info("拦截到本次请求{}", requestURI);
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",    //移动端发送短信
                "/user/login"        //移动端登录
        };
        //如果是true，证明是登录操作，放行
        if (check(urls, requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //2.判断session是否为空
        Long employee = (Long) request.getSession().getAttribute("employee");

        if (employee != null) {
            log.info("用户已登录，用户id为{}:",employee);
            BaseContext.setCurrentId(employee);
            //不等于空证明登陆过了，放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //2.1判断session是否为空
        Long user = (Long) request.getSession().getAttribute("user");
        if (user != null) {
            log.info("用户已登录，用户id为{}:",user);
            BaseContext.setCurrentId(user);
            //不等于空证明登陆过了，放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //未登录返回错误提示交给前端处理
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param urls
     * @param requestURL
     * @return
     */
    public boolean check(String[] urls, String requestURL) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURL);
            if (match) {
                return true;
            }
        }
        return false;
    }
}

